package cn.itcast.order.task;

import cn.itcast.feign.client.ItemClient;
import cn.itcast.hmall.pojo.item.Item;
import cn.itcast.hmall.pojo.order.Order;
import cn.itcast.hmall.pojo.order.OrderDetail;
import cn.itcast.order.mapper.orderDetailMapper;
import cn.itcast.order.service.ServiceOrder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;

@Component
public class OrderJob {
    @Autowired
    private ServiceOrder orderService;

    @Autowired
    private orderDetailMapper orderDetailMappers;

    @Autowired
    private ItemClient itemClient;

    @XxlJob("orderJob")
    public void orderJob(){

        System.err.println("测试定时取消订单");
//        //当前时间
//        Date nowDate = new Date();
//        //设置30分钟
//        long time=30*60*1000;
////        //测试用两分钟
////        long time=2*60*1000;
//        long closeTime= nowDate.getTime()- time;

        //查询订单表
        LambdaQueryWrapper<Order> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Order::getStatus,1);
//                .le(Order::getCreateTime,closeTime);
        //获取未支付的订单
        List<Order> orderList = orderService.list(wrapper);
        for (Order order : orderList) {
            //设置订单状态为5 取消订单
            Date date = new Date();
            Date createTime = order.getCreateTime();
            long time = ChronoUnit.MINUTES.between(Instant.ofEpochMilli(createTime.getTime()), Instant.ofEpochMilli(date.getTime()));


            if (time>30L){
                order.setStatus(5);
                //查询订单详细信息
//            LambdaQueryWrapper<OrderDetail> wrapper1 = Wrappers.lambdaQuery();
//            wrapper1.eq(OrderDetail::getOrderId,order.getId());
                OrderDetail orderDetail = orderDetailMappers.selectById(order.getId());
                //获取商品id
                Long itemId = orderDetail.getItemId();

                //根据商品id查询商品信息 并修改库存
                Item item = itemClient.additem(itemId.toString());
                item.setStock(item.getStock()+orderDetail.getNum());


                //设置商品信息
                itemClient.resultDTO(item);
            }



        }
    }
}